import editForm from "../form.vue";
import { message } from "@/utils/message";
import { getTableMenuList, deleteMenu, updateMenu, addMenu } from "@/api/menu";
import { addDialog } from "@/components/ReDialog";
import { ref, onMounted, h } from "vue";
import { type FormItemProps } from "../utils/types";
import { menuTypeColorEnum, menuTypeEnum, menuVisibleEnum } from "@/enums/menu";
import { commonStatusColorEnum, commonStatusEnum } from "@/enums/enum";

export function useMenu() {
  const formRef = ref();
  const dataList = ref([]);
  const menuList = ref([]);
  const parentMenuList = ref([]);
  const loading = ref(true);
  // const { tagStyle } = usePublicHooks();

  const columns: TableColumnList = [
    {
      label: "标题",
      prop: "title"
      // align: "left"
    },
    {
      label: "组件名",
      prop: "name",
      minWidth: 70
    },
    {
      label: "路径",
      prop: "path",
      minWidth: 120
    },
    {
      label: "权限",
      prop: "perms",
      minWidth: 70
    },
    {
      label: "图标",
      prop: "icon",
      minWidth: 70
    },
    {
      label: "显隐",
      prop: "visible",
      minWidth: 50,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} type={commonStatusColorEnum[row.visible]}>
          {menuVisibleEnum[row.visible]}
        </el-tag>
      )
    },
    {
      label: "类型",
      prop: "type",
      minWidth: 50,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} type={menuTypeColorEnum[row.type]}>
          {menuTypeEnum[row.type]}
        </el-tag>
      )
    },
    {
      label: "排序",
      prop: "sort",
      minWidth: 50
    },
    {
      label: "描述",
      prop: "remark",
      minWidth: 70
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 50,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} type={commonStatusColorEnum[row.status]}>
          {commonStatusEnum[row.status]}
        </el-tag>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 160,
      slot: "operation"
    }
  ];

  /**
   * 菜单格式处理
   * @param data
   * @returns
   */
  function menuFormatHandel(data: Array<any>) {
    const resData = [];
    const copyData = [...data];

    copyData.forEach(t => {
      if (t?.type !== 10) {
        const obj: any = {};
        obj.value = t.id;
        obj.label = t.title;
        if (t?.children?.length > 0) {
          obj.children = menuFormatHandel(t.children);
        }
        resData.push(obj);
      }

      // 只存父级的菜单
      if (t?.type === 0) {
        const obj: any = {};
        obj.value = t.id;
        obj.label = t.title;
        parentMenuList.value.push(obj);
      }
    });

    return resData;
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getTableMenuList(); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    menuList.value = [];
    parentMenuList.value = [];
    menuList.value = menuFormatHandel(data);
    // if (!isAllEmpty(form.villageName)) {
    //   // 前端搜索部门名称
    //   newData = newData.filter(item => item.name.includes(form.villageName));
    // }
    // if (!isAllEmpty(form.houseStatus)) {
    //   // 前端搜索状态
    //   newData = newData.filter(item => item.houseStatus === form.houseStatus);
    // }
    // dataList.value = handleTree(newData); // 处理成树结构
    dataList.value = data;
    // pagination.total = data?.total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}菜单`,
      props: {
        formInline: {
          id: row?.id ?? null,
          parentId: row?.parentId ?? null,
          title: row?.title ?? "",
          name: row?.name ?? "",
          icon: row?.icon ?? "",
          sort: row?.sort ?? null,
          path: row?.path ?? "",
          type: row?.type ?? 0,
          visible: row?.visible ?? null,
          status: row?.status ?? null,
          perms: row?.perms ?? null,
          remark: row?.remark ?? null,
          menuOptions: menuList.value,
          parentMenuOptions: parentMenuList.value
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        // const pathUrl = formRef.value.pathUrl;
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了资产拥有人为${curData.title}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              const res = await addMenu(curData);
              console.log(res);
              if (res.code === 200) {
                if (res.code == 201) {
                  message(`新增失败`, {
                    type: "error"
                  });
                } else {
                  chores();
                }
              }
            } else {
              // curData.imageUrl = pathUrl;
              // 实际开发先调用编辑接口，再进行下面操作
              const res = await updateMenu(curData);

              if (res.code === 200) {
                if (res.code == 201) {
                  message(`更新失败`, {
                    type: "error"
                  });
                } else {
                  chores();
                }
              }
            }
          }
        });
      }
    });
  }

  function addMenuHandel() {
    openDialog();
  }

  async function handleDelete(row) {
    const { data } = await deleteMenu([row.id]);
    console.log(data);
    message(`您删除了部门名称为${row.name}的这条数据`, { type: "success" });
    onSearch();
  }

  onMounted(() => {
    onSearch();
  });

  return {
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    /** 新增、编辑部门 */
    openDialog,
    /** 删除部门 */
    handleDelete,
    addMenuHandel
  };
}
